# -*- coding:utf-8 -*-
import time

def binduser(rsp):
    " 绑定用户 临时方案 "
    session.sip_isp_loginurl = rsp.headers['sip_isp_loginurl']
    session.sip_redirecturl = HOST+URL(r=request)
    redirect(URL(r=request, c='start', f='binduser'))

def check_user():
    if session.user_name and session.user_name != None and time.time()<session.user_expires:
        return True
    else:
        return False

def assign_username():
    user_name = sip.alisoft.udb.getDomainLoginId(domainid = '3', userid = userId,)['result']
    if not user_name:
        user_name = sip.alisoft.udb.getDomainLoginId(domainid = '1', userid = userId,)['result']
        if not user_name:
            user_name = sip.alisoft.udb.getDomainLoginId(domainid = '0', userid = userId,)['result']
            if not user_name:
                user_name = 'wowo'
    session.user_name = user_name
    # 当前时间 + 12小时
    session.user_expires = time.time() + 43200.0
    

def set_user():
    if check_user():
        global appInstanceId, token, userId
        appInstanceId = session.appInstanceId
        token = session.token
        userId = session.userId
        session.user_expires = time.time() + 43200.0
    elif request.vars.keys() == ['app_instance_id', 'token', 'user_id', 'app_id', 'target']:
        appInstanceId = session.appInstanceId = request.vars['app_instance_id']
        token = session.token = request.vars['token']
        userId = session.userId = request.vars['user_id']
        validate_user = sip.alisoft.validateUser(appInstanceId, userId, token)
        logger('validate_user', validate_user.keys())
        if 'response' in validate_user.keys():
            if validate_user['response'] == 1:
                assign_username()
        elif 'String' in validate_user.keys():
            if validate_user['String'] == 1:
                assign_username()
        elif request.controller == 'start' and request.function == 'index': 
            pass
        else:
            redirect(URL(r=request, c='start', f='index'))
    elif request.controller == 'start' and request.function == 'index': 
        pass
    else:
        session.current_url = HOST+request.env.path_info
        redirect(URL(r=request, c='start', f='index'))

    " check ISP username "
    if 'isp_username' in request.vars.keys():
        session.isp_username = request.vars['isp_username']
        redirect(URL(r=request))

    
def check_session(func):
    if not sip.check_session():
        session.sip_redirecturl = HOST+URL(r=request)
        session.sip_isp_loginurl = sip.get_url('login','login')
        redirect(URL(r=request, c='start', f='binduser'))
    else:
        return func


set_user()
